package com.gmall.product.service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gmall.common.result.PageInfo;
import com.gmall.common.result.Result;
import com.gmall.model.product.BaseCategory;
import com.gmall.model.product.BaseTrademark;
import com.gmall.model.product.SkuInfo;
import com.gmall.product.mapper.SkuInfoMapper;
import com.gmall.product.service.cache.BaseCategoryCacheService;
import com.gmall.product.service.cache.BaseTrademarkCacheService;
import com.gmall.rabbitmq.config.Sku_Queue_Config;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class SkuService {

    @Autowired
    SkuInfoMapper skuInfoMapper;

    @Autowired
    BaseTrademarkCacheService trademarkCacheService;

    @Autowired
    BaseCategoryCacheService baseCategoryCacheService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    public Result<PageInfo<SkuInfo>> findPage(
            Integer pageNo, Integer pageSize, Map<String,String> searchMap) {

        IPage<SkuInfo> page = new Page<>(pageNo, pageSize);

        QueryWrapper<SkuInfo> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<SkuInfo> lambda = queryWrapper.lambda();

        /* 可以为空 searchMap
        {
            "skuName":"",
            "catalog3Id":0,
            "tmId":0
        }
         */
        if(searchMap!=null){
            String skuName = searchMap.get("skuName");
            if(!StringUtils.isEmpty(skuName)){
                lambda.like(SkuInfo::getSkuName,skuName);
            }
            String catalog3Id = searchMap.get("catalog3Id");
            if(!StringUtils.isEmpty(catalog3Id)){
                lambda.eq(SkuInfo::getCategory3Id,catalog3Id);
            }
            String tmId = searchMap.get("tmId");
            if(!StringUtils.isEmpty(tmId)){
                lambda.eq(SkuInfo::getTmId,tmId);
            }
        }
        IPage<SkuInfo> skuInfoIPage = skuInfoMapper.selectPage(page, lambda);

        List<SkuInfo> records = skuInfoIPage.getRecords();

//        for(SkuInfo skuInfo:records){
//            BaseTrademark trademark = trademarkCacheService.getTrademarkById(skuInfo.getTmId());
//            skuInfo.setTmName(trademark.getTmName());
//
//            BaseCategory category = baseCategoryCacheService.getBaseCategoryById(skuInfo.getCategory3Id());
//            skuInfo.setCategory3Name(category.getName());
//        }
        records.forEach((SkuInfo skuInfo)->{
            BaseTrademark trademark = trademarkCacheService.getTrademarkById(skuInfo.getTmId());
            skuInfo.setTmName(trademark.getTmName());

            BaseCategory category = baseCategoryCacheService.getBaseCategoryById(skuInfo.getCategory3Id());
            skuInfo.setCategory3Name(category.getName());
        });

        PageInfo pageInfo = new PageInfo();
        pageInfo.setTotal(skuInfoIPage.getTotal());

        pageInfo.setRecords(records);

        return Result.ok(pageInfo);
    }

    public Result<String> onSale(Long skuId) {

        //条件修改
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);
        //RabbitMQ 解耦，发送上架消息
        rabbitTemplate.convertAndSend(Sku_Queue_Config.EXCHANGE_DIRECT_GOODS,
                Sku_Queue_Config.ROUTING_GOODS_UPPER,skuId);
        return Result.ok("上架成功");
    }

    public Result<String> cancelSale(Long skuId) {

        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
        //RabbitMQ 解耦，发送下架消息
        rabbitTemplate.convertAndSend(Sku_Queue_Config.EXCHANGE_DIRECT_GOODS,
                Sku_Queue_Config.ROUTING_GOODS_LOWER,skuId);
        return Result.ok("下架成功");
    }


    public List<SkuInfo> getSkuInfoListAfterDateTime(Map searchMap) {

        /**
         * {
         *  "lastSyncDateTime":2024-08-12 12:23:05
         * }
         */
        //
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        QueryWrapper<SkuInfo> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<SkuInfo> lambda = queryWrapper.lambda();
        lambda.eq(SkuInfo::getIsSale,1);//
        if(searchMap!=null){
            String lastSyncDateTime_str = (String)searchMap.get("lastSyncDateTime");
            if(!StringUtils.isEmpty(lastSyncDateTime_str)){//增量数据
                Date lastSyncDateTime = null;
                try {
                    lastSyncDateTime = simpleDateFormat.parse(lastSyncDateTime_str);
                    lambda.ge(SkuInfo::getUpdateTime,lastSyncDateTime);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return skuInfoMapper.selectList(queryWrapper);//全量数据
    }

    public Result<SkuInfo> getSkuInfoById(Long id) {

        return Result.ok(skuInfoMapper.selectById(id));
    }
}
